import { message, Tooltip, Tree, Modal, Form, Input, Button } from 'antd';
import { PlusCircleOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import React, { useEffect, useState } from 'react';
import $ from 'jquery';
import intl from 'react-intl-universal';
import './classify.css';


const Classify = () => {
  const [tempData, setTempData] = useState([]);             // 后端接收数据
  const [classifyData, setClassifyData] = useState([]);     // 处理后的分类数据
  const [handleData, setHandleData] = useState(false);      // 是否处理tempData

  // 获取后台数据
  const [hasChange, setHasChange] = useState(true);
  useEffect(() => {
    const getClassification = () => {
      $.ajax({
        url: '/home/classify',
        type: 'post',
        dataType: 'json',
        success: function(result) {
          if (result.status === 1) {
            setTempData(result.data);
            setHandleData(true);
          } else {
            message.info(intl.get('failedToQuery'));
          }
        },
        error: function(err) {
          alert(JSON.stringify(err));
        },
      });
    };
    hasChange && getClassification();
    setHasChange(false);
  }, [hasChange]);


// 处理从后端接收的数据，成树形结构
const createTree = (data) => {
  let treeData = [];
  // 获取一级节点
  let roots = data.filter(element => element.parent === 0);
  treeData.push(...roots);
  // 从一级节点开始，获取每个元素的子元素放到该元素的children属性中
  const getChildren = (result, data) => {
    result.forEach((element, index) => {
      element.children = data.filter((item, index) => item.parent === element.kid);
      if (element.children.length > 0) {
        getChildren(element.children, data);
      }
    });
  }
  getChildren(treeData, data);
  return treeData;
};


// 再次处理数据，成官方文档中treeData格式
const createTreeData = (data) => {
  let treeData = [];
  data.map((item) => {
    let node = {
      key: item.kid,
      title: item.kname,
      children: createTreeData(item.children),
      description: item.kdescription,
      parent: item.parent,
    };
    treeData.push(node);
  });
  return treeData;
};


  // 调用处理数据的方法
  useEffect(() => {
    let treeData = [];
    if (handleData) {
      treeData = createTree(tempData);
      treeData = createTreeData(treeData);
      setClassifyData(treeData);
    }
    setHandleData(false);
  }, [handleData]);


  // 增、改分类节点时的Modal
  const [modalWidth, setModalWidth] = useState("520px");
  const [showModal, setShowModal] = useState({
    ifShow: false,
    title: 'Modal',
    children: {},
  });
  const hideModal = () => {
    setModalWidth("520px");
    setShowModal({
      ifShow: false,
      title: 'Modal',
      children: {},
    });
  };


  const layout = { labelCol: {span: 8,}, wrapperCol: {span: 16,}, };

  // 增
  const doAddClassify = (data) => {
    $.ajax({
      url: '/home/classify/add',
      type: 'post',
      data: data,
      dataType: 'json',
      success: function(result) {
        if (result.status === 1) {
          message.success(intl.get('succeedToAdd'));
          setHasChange(true);
          hideModal();
        } else {
          message.info(intl.get('failedToAdd'));
        }
      },
      error: function(err) {
        alert('分类名称重复');
      }
    });
  };

  const addNode = (node) => {
    // console.log('add',node)
    setShowModal({
      ifShow: true,
      title: intl.get('addClassifyNode'),
      children: 
        <Form {...layout} validateMessages={{ required: 'Name is required!', }} onFinish={doAddClassify} initialValues={{parent:node.key}}> 
          <Form.Item name='name' label="Name" rules={[{required: true, max: 32},]}>
            <Input />
          </Form.Item>
          <Form.Item name='description' label="Description">
            <Input.TextArea />
          </Form.Item>
          <Form.Item name='parent'>
            <Input hidden={true} />
          </Form.Item>
          <Form.Item wrapperCol={{ ...layout.wrapperCol, offset: 8 }}>
            <Button type="primary" htmlType="submit" className='doAddClassify'>{intl.get('submit')}</Button>
          </Form.Item>
        </Form>,
    });
  };


  // 改
  const doUpdateClassify = (data) => {
    $.ajax({
      url: '/home/classify/update',
      type: 'post',
      data: data,
      dataType: 'json',
      success: function(result) {
        if (result.status === 1) {
          message.success(intl.get('succeedToUpdate'));
          setHasChange(true);
          hideModal();
        } else {
          message.info(intl.get('failedToUpdate'));
        }
      },
      error: function(err) {
        alert('分类名称重复');
      }
    });
  };

  const modifyNode = (node) => {
    // console.log('modify', node)
    setShowModal({
      ifShow: true,
      title: intl.get('updateClassifyNode'),
      children: 
        <Form {...layout} validateMessages={{ required: 'Name is required!', }} onFinish={doUpdateClassify} 
        initialValues={{id:node.key, name:node.title, description:node.description, parent:node.parent}}>
          <Form.Item name='id'>
            <Input hidden={true} />
          </Form.Item>
          <Form.Item name='name' label="Name" rules={[{required: true, max: 32},]}>
            <Input />
          </Form.Item>
          <Form.Item name='description' label="Description">
            <Input.TextArea />
          </Form.Item>
          <Form.Item name='parent'>
            <Input hidden={true} />
          </Form.Item>
          <Form.Item wrapperCol={{ ...layout.wrapperCol, offset: 8 }}>
            <Button type="primary" htmlType="submit" className='doUpdateClassify'>{intl.get('submit')}</Button>
          </Form.Item>
        </Form>,
    });
  };


  // 删，有子节点的分类不允许删除
  // const getAjaxData = (node) => {           // 递归删除子节点
  //   let data = [];
  //   if (node.children.length > 0) {
  //     node.children.map((child) => {
  //       data.push(child.key);             
  //       data = [...data, ...getAjaxData(child)];
  //     });
  //   }
  //   return data;
  // };

  const deleteNode = (node) => {
    let data = [];
    data.push(node.key);                    // 一级节点
    if (node.children.length !== 0) {
      message.info('有子分类，不允许删除');
      return;
    }
    // data = [...data, ...getAjaxData(node)]; // 子节点
    // console.log('delete',data)
    $.ajax({
      url: '/home/classify/delete',
      type: 'post',
      data: {ids: data},
      traditional: true,
      dataType: 'json',
      success: function(result) {
        if (result.status === 1) {
          message.success(intl.get('succeedToDelete'));
          setHasChange(true);
        } else {
          message.info(intl.get('failedToDelete'));
        }
      },
      error: function(err) {
        alert(JSON.stringify(err));
      }
    })
  }; 


  // 对节点的操作（不建议在处理treeData时，在title中添加操作）
  const titleRender = (node) => {
    let res;
    res = (
      <div style={{display:'flex'}}>
        <span>{node.title}</span>
        <span>
          <Tooltip title='添加'>
            <PlusCircleOutlined style={{marginLeft:'20px'}} onClick={() => addNode(node)} />
          </Tooltip>
          <Tooltip title='编辑'>
            <EditOutlined style={{marginLeft:'8px'}} onClick={() => modifyNode(node)} />
          </Tooltip>
          <Tooltip title='删除'>
            <DeleteOutlined style={{marginLeft:'8px'}} onClick={() => deleteNode(node)} />
          </Tooltip>
        </span>
      </div>
    );
    return res;
  }


  return (
    <div style={{backgroundColor:'#fff', minHeight:'600px'}}>
      <Button type='primary' style={{width:'120px', height:'30px'}} onClick={() => addNode({key: 0})}>
        {intl.get('addRootClassify')}
      </Button>
      {/* 先判断数据是否存在，才能默认展开节点 */}
      {(classifyData.length > 0) ? 
        <Tree style={{margin:'20px 20px', fontSize:'16px'}} showLine={true} defaultExpandAll={true} autoExpandParent={true} 
        treeData={classifyData} titleRender={titleRender} /> :
        <div />
      }
      <Modal destroyOnClose='true' title={showModal.title} visible={showModal.ifShow} width={modalWidth} footer={false}
        onOk={hideModal} onCancel={hideModal} okText={intl.get('yes')} cancelText={intl.get('no')}>
        {showModal.children}
      </Modal>
    </div>
  );
};

export default Classify;